﻿/**
 * 
 * F. Mehmet ARSLAN (c) 2015
 * fmehmetarslan46@gmail.com
 *  
 **/
using ServiceState.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace ServiceState.Helper
{
    public class LogManager
    {
        public static string Filepath { get; set; }
        private static string fileName;
        private static object locker = new Object();
        private static DateTime createdDate = DateTime.Now;

        public static String GetLogLink()
        {
            return "/Log/" + fileName.Substring(fileName.LastIndexOf("\\"));
        }
        public static String[] GetLog()
        {
            try
            {
                if (String.IsNullOrEmpty(fileName))
                    return new String[0];
                return File.ReadAllLines(fileName);
            }
            catch { return new String[0]; }
        }
        public static void WriteStateChangeLog(Service oldService, Service newService)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.ToShortDateString());
            sb.Append(" ");
            sb.Append(DateTime.Now.ToLongTimeString());
            sb.Append(" - ");
            sb.Append(oldService.LongDescription);
            sb.Append(" state change ");
            sb.Append(oldService.StatusCode.ToString());
            sb.Append("[");
            sb.Append(oldService.StatusCode.GetHashCode().ToString());
            sb.Append("]");
            sb.Append(" => ");
            sb.Append(newService.StatusCode.ToString());
            sb.Append("[");
            sb.Append(newService.StatusCode.GetHashCode().ToString());
            sb.Append("]");
            sb.Append(" - URL: ");
            sb.Append(oldService.getUrl);
            lock (locker)
            {
                if ((DateTime.Now - createdDate).TotalDays>0)
                {
                    StringBuilder fileNameSb = new StringBuilder();
                    fileNameSb.Append(Filepath);
                    fileNameSb.Append("\\");
                    fileNameSb.Append(DateTime.Now.ToShortDateString().Replace("\\", ".").Replace("/", "."));
                    fileNameSb.Append("#state");
                    fileNameSb.Append(".log");
                    fileName = fileNameSb.ToString();
                    /*if (!File.Exists(fileName))
                    {
                        File.Create(fileName).Dispose();
                    }*/
                }                
                using (FileStream file = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8))
                {
                    writer.WriteLineAsync(sb.ToString());
                }
            }
        }
    }
}